﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using tuwien.auto.eibclient;
using KNXFramework.Logging;

namespace KNXFramework.KNXObjects.ValueObjects
{
    internal class StringObjectValue : IValueObject
    {
        private string m_Value;

        #region Constructors
        public StringObjectValue(string value)
        {
            if (value.Length > 14)
                throw new ApplicationException("StringObjectValue: Bad value (too long). Val : " + value);

            m_Value = value;
        }
        public StringObjectValue(EIBBuffer buffer)
        {
            if (buffer.data.Length < 2)
            {
                CustomLogger.WriteErrorEntry("Invalid packet received for StringObjectValue (too short)");
                return;
            }
            m_Value = Encoding.ASCII.GetString(buffer.data, 2, buffer.data.Length - 2);

        }
        #endregion

        public override string ToString()
        {
            return m_Value;
        }

        #region IValueObject Members

        public void AdaptBufferBeforeSending(bool isWrite, tuwien.auto.eibclient.EIBBuffer buffer)
        {
            byte[] stringArray = Encoding.ASCII.GetBytes(m_Value);
            byte[] b = new byte[16];
            b[0] = 0;
            b[1] = buffer.data[1];
            for (int i = 0; i < stringArray.Length; i++)
                b[i + 2] = stringArray[i];

            buffer.data = b;
        }

        #endregion

        #region IEquatable<IValueObject> Members

        public bool Equals(IValueObject other)
        {
            StringObjectValue otherVal = other as StringObjectValue;
            bool equality = false;
            if (otherVal != null)
                equality = m_Value.Equals(otherVal.m_Value);
            return equality;
        }

        #endregion
    }
}
